package attribute

import (
	"context"

	"mall/common/modelx"
	"mall/common/utils/pointy"
	"mall/service/backend/common/errorx"
	"mall/service/backend/common/i18n"
	"mall/service/product/model"
	"mall/service/product/rpc/internal/svc"
	"mall/service/product/rpc/internal/utils/errorhandler"
	"mall/service/product/rpc/types/product"

	"github.com/zeromicro/go-zero/core/logx"
)

type BackendGetAttributeByIdLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewBackendGetAttributeByIdLogic(ctx context.Context, svcCtx *svc.ServiceContext) *BackendGetAttributeByIdLogic {
	return &BackendGetAttributeByIdLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *BackendGetAttributeByIdLogic) BackendGetAttributeById(in *product.AttributeIdReq) (*product.AttributeInfo, error) {
	if in.Id == 0 {
		return nil, errorx.NewInvalidArgumentError(i18n.ValidationError)
	}

	res, err := l.svcCtx.Attribute.FindOne(l.ctx, in.Id)
	if err != nil {
		return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
	}

	var options []*product.AttributeOptionInfo
	if in.WithOption != nil && *in.WithOption > 0 {
		filterMap := make(map[string]map[string][]any)
		filterMap[model.AttributeOptionColumns.AttributeID] = map[string][]any{
			"equalTo": {in.Id},
		}
		list, _, err := l.svcCtx.Attribute.GetOptionList(l.ctx, model.M{}, -1, filterMap)
		if err != nil {
			return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
		}

		if len(list) > 0 {
			for _, v := range list {
				options = append(options, &product.AttributeOptionInfo{
					Id:          &v.OptionID,
					AttributeId: &v.AttributeID,
					Name:        &v.Name,
					Slug:        &v.Slug,
					Sort:        pointy.GetPointer(uint32(v.Sort)),
					Status:      pointy.GetPointer(uint32(v.Status)),
					CreatedAt:   pointy.GetPointer(modelx.FormatTime(v.CreatedAt, "")),
					UpdatedAt:   pointy.GetPointer(modelx.FormatTime(v.UpdatedAt, "")),
					DeletedAt:   pointy.GetPointer(modelx.FormatNullDotTime(v.DeletedAt, "")),
				})
			}
		}
	}

	return &product.AttributeInfo{
		Id:          &res.ID,
		TermId:      &res.TermID,
		Taxonomy:    &res.Taxonomy,
		IsVariation: pointy.GetPointer(uint32(res.IsVariationAttribute)),
		Name:        &res.Name,
		Slug:        &res.Slug,
		HasMedia:    pointy.GetPointer(uint32(res.HasImage)),
		Sort:        pointy.GetPointer(uint32(res.Sort)),
		Status:      pointy.GetPointer(uint32(res.Status)),
		CreatedAt:   pointy.GetPointer(modelx.FormatTime(res.CreatedAt, "")),
		UpdatedAt:   pointy.GetPointer(modelx.FormatTime(res.UpdatedAt, "")),
		DeletedAt:   pointy.GetPointer(modelx.FormatNullDotTime(res.DeletedAt, "")),
		Options:     options,
	}, nil
}
